package com.dongdongshop.utils;

import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Map;
import java.util.Optional;

/**
 * HttpClient 工具类
 */
public class HttpClientUtil {

    private static final CloseableHttpClient httpclient;

    //编码格式
    public static final String CHARSET = "utf-8";

    // 采用静态代码块，初始化超时时间配置，再根据配置生成默认httpClient对象
    static {
        RequestConfig config = RequestConfig.custom()
                .setConnectTimeout(60000)
                .setSocketTimeout(15000)
                .build();
        httpclient = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
    }

    /**
     * @param url    请求URL 地址
     * @param params 请求参数
     * @return 响应内容
     */
    public static String doGet(String url, Map<String, String> params) {
        return doGet(url, params, CHARSET);
    }

    /**
     * @param url    请求URL 地址
     * @param params 请求参数
     * @return 响应内容
     */
    public static String doPost(String url, Map<String, String> params) {
        return doPost(url, params, CHARSET);
    }


    /**
     * @param url    请求URL 地址
     * @param params 请求参数
     * @param code   编码格式
     * @return 响应内容
     */
    public static String doGet(String url, Map<String, String> params, String code) {
        if (url == null && !"".equals(url)) // 判断地址是否空
            return null;
        try {
            URIBuilder uriBuilder = getUriBuilder(url, params);// 添加参数

            HttpGet httpGet = new HttpGet(uriBuilder.build()); // 创建 HttpGet 实例

            HttpEntity entity = getHttpEntity(httpclient.execute(httpGet),code);//获取 响应信息

            Optional<String> strCode = Optional.ofNullable(code);
            strCode.orElse(CHARSET);

            return EntityUtils.toString(entity, code);
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * @param url    请求URL 地址
     * @param params 请求参数
     * @param code   编码格式
     * @return 响应内容
     */
    public static String doPost(String url, Map<String, String> params, String code) {
        if (url == null && !"".equals(url)) // 判断地址是否空
            return null;
        try {
            URIBuilder uriBuilder = getUriBuilder(url, params); // 添加参数

            HttpPost httpPost = new HttpPost(uriBuilder.build()); // 创建 HttpGet 实例

            HttpEntity entity = getHttpEntity(httpclient.execute(httpPost),code);//获取 响应信息

            Optional<String> strCode = Optional.ofNullable(code);
            strCode.orElse(CHARSET);

            return EntityUtils.toString(entity, code);
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    //获取 响应信息
    private static HttpEntity getHttpEntity(CloseableHttpResponse execute, String code) {
        CloseableHttpResponse response = execute; //发送实例
        if (response.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException("状态码是" + response.getStatusLine().getStatusCode());
        }
        //获取响应信息
        HttpEntity entity = response.getEntity();

        return entity;
    }

    //添加 参数
    private static URIBuilder getUriBuilder(String url, Map<String, String> params) throws URISyntaxException {
        URIBuilder uriBuilder = new URIBuilder(url);//创建一个 uriBuilder

        if (params != null && !params.isEmpty()) { // 判断参数是否空
            for (Map.Entry<String, String> entry : params.entrySet()) {
                String key = entry.getKey();
                if (key != null && uriBuilder != null) {
                    uriBuilder.addParameter(entry.getKey(), params.get(key));
                }
            }
        }
        return uriBuilder;
    }


}
